package com.synway.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SpiderHandler {
    public static AmqpTemplate rabbitTemplate;


    public static void spiderHandler(String rootPath, String pythonEnv, String py){
        log.info(py + "...spider start...");
        try {
            String[] args2 = new String[]{pythonEnv, rootPath + py, "cd"};
            Process process = Runtime.getRuntime().exec(args2);
            StreamThread errorGobbler = new StreamThread(process.getErrorStream(),"Error");
            StreamThread outputGobbler = new StreamThread(process.getErrorStream(),"Output");
            errorGobbler.start();
            outputGobbler.start();
            process.waitFor(1, TimeUnit.HOURS);
            log.info(py + "..spider end...");
            //通知mq爬虫结束
            rabbitTemplate.convertAndSend("SPIDER_QUEUE",py.split("\\.")[0]);
        } catch (IOException | InterruptedException e) {
            log.error(py + "..spider error..." + e);
        }
    }

    public static void ptoxyHandler(String rootPath,String pythonEnv,String py){
        String result = "";
        log.info("proxy start...");
        try {
            String[] args2 = new String[]{pythonEnv, rootPath + py};
            Process process = Runtime.getRuntime().exec(args2);
            InputStreamReader ir = new InputStreamReader(process.getInputStream(), "gbk");
            BufferedReader input = new BufferedReader(ir);
            while ((result = input.readLine()) != null) {
                log.info(result);
            }
            process.waitFor();
            input.close();
            ir.close();
            log.info("proxy end...");
            //顺便删除一下python log文件
            File file = new File(rootPath+"log/log.txt");
            if(file.exists()){
                file.delete();
            }
        } catch (IOException | InterruptedException e) {
            log.error("proxy error..." + e);
        }
    }

}
